package com.fullertontech.framework.logger;

import ch.qos.logback.classic.Logger;
import ch.qos.logback.classic.LoggerContext;
import ch.qos.logback.classic.PatternLayout;
import ch.qos.logback.classic.spi.Configurator;
import ch.qos.logback.classic.spi.ILoggingEvent;
import ch.qos.logback.core.ConsoleAppender;
import ch.qos.logback.core.encoder.LayoutWrappingEncoder;
import ch.qos.logback.core.rolling.RollingFileAppender;
import ch.qos.logback.core.rolling.SizeAndTimeBasedFNATP;
import ch.qos.logback.core.rolling.TimeBasedRollingPolicy;
import ch.qos.logback.core.spi.ContextAwareBase;
import ch.qos.logback.core.util.FileSize;

public class LogbackConfigurator extends ContextAwareBase implements Configurator{


  @Override
  public void configure(LoggerContext lc) {
    addInfo("Setting up default configuration.");
    // 清除loggerContext已加载配置，重新加载
    lc.reset();
    lc.putProperty("log_home", "D:\\logs");
   // lc.putObject(LoggingSystem.class.getName(), 1);
    ConsoleAppender<ILoggingEvent> ca = new ConsoleAppender<ILoggingEvent>();
    ca.setContext(lc);
    ca.setName("console");
    LayoutWrappingEncoder<ILoggingEvent> encoder = new LayoutWrappingEncoder<ILoggingEvent>();
    encoder.setContext(lc);

    // same as 
    // PatternLayout layout = new PatternLayout();
    // layout.setPattern("%d{HH:mm:ss.SSS} [%thread] %-5level %logger{36} - %msg%n");
    PatternLayout layout = new PatternLayout();
    layout.setPattern("%msg%n");
    layout.setContext(lc);
    layout.start();
    encoder.setLayout(layout);
    
    ca.setEncoder(encoder);
    ca.start();
    
    RollingFileAppender<ILoggingEvent> rollingFileAppender=new RollingFileAppender<ILoggingEvent>();
    rollingFileAppender.setFile(lc.getProperty("log_home")+"/ams-web.log");
    TimeBasedRollingPolicy<ILoggingEvent> policy=new TimeBasedRollingPolicy<ILoggingEvent>();
    policy.setFileNamePattern("${log_home}/ams-web-%d{yyyy-MM-dd}.%i.log");
    SizeAndTimeBasedFNATP<ILoggingEvent> sizeAndTimeBasedFNATP=new SizeAndTimeBasedFNATP<ILoggingEvent>();
    sizeAndTimeBasedFNATP.setMaxFileSize(new FileSize(50*1024*1024));//50M
    policy.setTimeBasedFileNamingAndTriggeringPolicy(sizeAndTimeBasedFNATP);
    rollingFileAppender.setRollingPolicy(policy);
    rollingFileAppender.setEncoder(encoder);
    
    Logger rootLogger = lc.getLogger(Logger.ROOT_LOGGER_NAME);
    rootLogger.addAppender(ca);
  }

}
